import os

from django.db import models
from django.db.models.signals import post_delete
from django.contrib.auth.models import User


class Image(models.Model):
    """
    上传图片模型
    """

    user = models.ForeignKey(
        User,
    )
    caption = models.CharField(
        max_length=100,
        help_text="简要的描述图片",
    )
    image = models.ImageField(
        upload_to='images/%Y/%m/%d',
    )
    upload_date = models.DateTimeField(
        auto_now_add=True,
    )

    def image_url(self):
        return self.image.url
    image_url.short_description = '路径'
    image_url.allow_tags = True

    def preview(self):
        return '<img src="%s" width="100px" />' % self.image.url
    preview.short_description = '预览'
    preview.allow_tags = True

    def __str__(self):
        return self.caption

    @models.permalink
    def get_absolute_url(self):
        return ('images:view', (), {
            'id': self.id,
        })

    class Meta:
        ordering = ('-upload_date',)


def delete_file(sender, **kwargs):
    image = kwargs['instance']
    os.remove(image.image.path)

post_delete.connect(delete_file, sender=Image)
